package org.thss.petri.gef.commands;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.gef.commands.Command;
import org.thss.petri.model.Arc;
import org.thss.petri.model.Node;
import org.thss.petri.model.PetriNet;

public class DeleteNodeCommand extends Command {
	private PetriNet net;
	private Node node;
	private List<Arc> sourceConnections = new ArrayList<Arc>();
	private List<Arc> targetConnections = new ArrayList<Arc>();
	
	public Node getNode() {
		return node;
	}
	public void setNode(Node node) {
		this.node = node;
		if (node != null) {
			this.net = node.getNet();
		}
	}
	
	@Override
	public void execute() {
		if (node == null) {
			return;
		}
		sourceConnections.addAll(node.getOutgoings());
		targetConnections.addAll(node.getIncomings());
		node.getOutgoings().clear();
		node.getIncomings().clear();
		for (Arc arc : sourceConnections) {
			arc.getTarget().getIncomings().remove(arc);
			net.getArcs().remove(arc);
		}
		for (Arc arc : targetConnections) {
			arc.getSource().getOutgoings().remove(arc);
			net.getArcs().remove(arc);
		}
		net.getNodes().remove(node);
	}
	
	@Override
	public void redo() {
		execute();
	}
	
	@Override
	public void undo() {
		node.getOutgoings().addAll(sourceConnections);
		node.getIncomings().addAll(targetConnections);
		for (Arc arc : sourceConnections) {
			arc.getTarget().getIncomings().add(arc);
			net.getArcs().add(arc);
		}
		for (Arc arc : targetConnections) {
			arc.getSource().getOutgoings().add(arc);
			net.getArcs().add(arc);
		}
		sourceConnections.clear();
		targetConnections.clear();
		net.getNodes().add(node);
	}
	
	
	
}
